<template>
  <div class="container">
    <!-- 搜索 -->
    <section class="search-label">
      <label class="padding-right--135">事件规则</label>
      <label class="padding-right--102">时间</label>
      <label class="padding-right--102">频率</label>
      <label class="padding-right--102">关系</label>
      <label class="padding-right--102">数值</label>
    </section>
    <section
      v-for="(firstItem, firstIndex) of search"
      :key="firstIndex"
      class="float-left--55"
    >
      <el-timeline
        :class="{
          'rule-block--node': search.length === 1 && search[0].length === 1
        }"
      >
        <el-timeline-item
          v-for="(secondItem, secondIndex) in search[firstIndex]"
          :key="secondIndex"
        >
          <div>
            <el-cascader
              v-model="secondItem.eventRules"
              :options="rules"
              :show-all-levels="false"
              :props="{ expandTrigger: 'hover' }"
              placeholder="请选择"
              size="small"
              class="width-180 margin-right--10"
              @change="rule => changeRule(secondItem, rule)"
            />
            <el-select
              v-model="secondItem.periodOfTime"
              placeholder="请选择"
              no-data-text="暂无数据"
              size="small"
              class="width-120 margin-right--10"
            >
              <el-option
                v-for="item in times"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-select
              v-model="secondItem.frequency"
              placeholder="请选择"
              no-data-text="暂无数据"
              size="small"
              class="width-120 margin-right--10"
            >
              <el-option
                v-for="item in frequencys"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-select
              v-model="secondItem.operator"
              placeholder="请选择"
              no-data-text="暂无数据"
              size="small"
              class="width-120 margin-right--10"
            >
              <el-option
                v-for="item in operators"
                :key="item"
                :label="item.label"
                :value="item"
              />
            </el-select>
            <el-input
              v-model="secondItem.value"
              :disabled="secondItem.disabled"
              placeholder="请输入"
              size="small"
              clearable
              class="width-160 margin-right--10"
              @change="
                () => {
                  secondItem.value = secondItem.value
                    .replace(/[^\d^\.]+/g, '')
                    .replace('.', '$#$')
                    .replace(/\./g, '')
                    .replace('$#$', '.');
                }
              "
            />
            <el-button
              v-if="firstIndex != 0 || secondIndex != 0"
              type="danger"
              plain
              icon="el-icon-delete"
              size="small"
              @click="
                deleteRule(secondItem.logOperator, firstIndex, secondIndex)
              "
            />
            <el-select
              v-if="firstIndex != 0 || secondIndex != 0"
              v-model="secondItem.logOperator"
              placeholder="请选择"
              size="small"
              class="width-80 margin-right--10"
              @change="
                operator =>
                  changeLog(secondItem, operator, firstIndex, secondIndex)
              "
            >
              <el-option
                v-for="item in logicalOperators"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </div>
        </el-timeline-item>
      </el-timeline>
    </section>
    <div :class="{ 'float-clear': totalLen !== 1 }" />
    <div
      :class="{ 'float-left': totalLen !== 1 }"
      class="padding-left--28"
      style="margin: -3px 0 15px"
    >
      <el-button
        v-if="
          search[newFirIndex][newSecIndex].eventRules[1] != undefined &&
            totalLen < 5
        "
        vtype="primary"
        plain
        icon="el-icon-plus"
        size="small"
        class="width-120 margin-right--15"
        @click="addRule"
        >新增按钮</el-button
      >
      <el-dropdown
        size="small"
        split-button
        type="primary"
        class="margin-right--15"
        @command="addFixedRule"
      >
        创建固定规则
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="BLACK">黑名单</el-dropdown-item>
          <el-dropdown-item command="GREY">灰名单</el-dropdown-item>
          <el-dropdown-item command="NOTSURE">疑似异常</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        class="width-120 margin-right--15"
        @click="rulesSearch('search')"
        >搜索</el-button
      >
      <el-button
        type="success"
        plain
        size="small"
        class="margin-right--15"
        @click="refreshSearch"
        >重置</el-button
      >
    </div>
    <div class="float-clear" />
    <!-- 固定规则显示 -->
    <section class="rules">
      <div :class="{ 'rules-body--isMore': isShowMore }" class="rules-body">
        <label for="固定规则">固定规则：</label>
        <p
          v-if="allFixedRules.length === 0"
          style="margin: 10px 0; display: inline-block; vertical-align: middle"
        >
          暂无数据
        </p>
        <div
          v-for="(item, index) of allFixedRules"
          :key="item.id"
          class="rules-body--item"
        >
          <span
            >【{{ ruleTypeDic[item.greyListOrBlackList] }}】{{ item.fixedRule }}
          </span>
          <i
            class="el-icon-delete-solid error cursor-pointer"
            @click="beforeDeleteRule(item.id)"
          />
          <el-divider
            v-if="index < allFixedRules.length - 1"
            direction="vertical"
          />
        </div>
        <el-button
          type="text"
          class="rules-body--more"
          @click="isShowMore = !isShowMore"
          >{{ isShowMore ? '收起' : '更多' }}
          <i
            :class="{
              'el-icon-arrow-up': isShowMore,
              'el-icon-arrow-down': !isShowMore
            }"
          />
        </el-button>
      </div>
    </section>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      ref="table"
      :data="tableData"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column label="编号" width="60" align="center">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="触发规则">
        <template slot-scope="scope">
          <span :title="scope.row.allRules">
            {{ scope.row.firstRuleGroupName }}
            {{ scope.row.ruleGroupNameList.length > 1 ? '...' : '' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="会员ID"
        align="center"
        width="120"
        prop="memberId"
      />
      <el-table-column
        label="会员昵称"
        align="center"
        width="150"
        prop="nickName"
      />
      <el-table-column
        label="身份证"
        align="center"
        width="300"
        prop="id_num"
      />
      <el-table-column label="手机号码" align="center" width="150" prop="tel" />
      <el-table-column
        label="零钱余额($)"
        align="center"
        width="150"
        prop="smallMoney"
      />

      <el-table-column :label="$t('status')" width="120" align="center">
        <template slot-scope="{ row }">
          <state-change
            :row="row"
            @changeStatusSuccee="rulesSearch"
            :pageName="pageName"
            :isShowWhite="false"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="goToDetail(scope.row.memberId)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-row style="text-align: right">
      <Pagination
        v-show="total > 0"
        :total="total"
        :page.sync="query.pageNum"
        :limit.sync="query.pageSize"
        @pagination="changePagination"
      />
    </el-row>
  </div>
</template>
<script>
import {
  ruleData,
  fixedRuleData,
  addfixedRule,
  delfixedRule,
  searchData,
  changeStatus
} from '@/api/user-exception-filtering/abnormal-behavior';
import { changeStatusJS, watchRouterJs } from './../mixins/common.js';
import Pagination from '@/components/Pagination';
import StateChange from '@/views/member-exception-filtering/components/StateChange.vue';
import { CHANGE_TYPE_MAP } from '@/constants/index.js'

const searchModel = [
  [
    {
      eventRules: [],
      periodOfTime: '', // 事件
      frequency: '', // 频率
      operator: '', // 关系
      value: null, // 数值
      disabled: true
    }
  ]
];

export default {
  name: 'AbnormalBehavior',
  components: {
    Pagination,
    StateChange
  },
  mixins: [changeStatusJS, watchRouterJs],
  data() {
    return {
      pageName: '会员异常筛选 / 异常行为筛选',
      CHANGE_TYPE_MAP,
      reasonType: null,
      visible: false,
      listLoading: false,
      tableData: [],
      total: 0,
      query: {
        pageNum: 1,
        pageSize: 50
      },
      allRulesData: {},
      allFixedRules: [], // 所有固定规则
      search: JSON.parse(JSON.stringify(searchModel)), // 搜索数据
      totalLen: 1, // 搜索规则的条数
      isShowMore: false,
      logicalOperators: ['AND', 'OR'],
      rules: [],
      times: [],
      frequencys: [],
      operators: []
    };
  },

  computed: {
    newFirIndex: function () {
      return this.search.length - 1;
    },
    newSecIndex: function () {
      return this.search[this.search.length - 1].length - 1;
    }
  },

  created() {
    this.getReasonTypeOptions();
  },

  activated() {
    if (!this.isCache) {
      this.refreshSearch();
      this.total = 0;
      this.tableData = [];
    }

    this.init();
  },

  methods: {
    // 初始化页面=1.获取规则数据 2.获取固定规则 3.获取异常行为数据
    init() {
      this.rules = [];
      ruleData()
        .then(result => {
          this.allRulesData = result.data;
          Object.keys(this.allRulesData).forEach(key => {
            const rules = {
              value: this.allRulesData[key][0].ruleType,
              label: key,
              children: this.allRulesData[key].map(item => {
                return { value: item.ruleName, label: item.ruleName };
              })
            };
            this.rules.push(rules);
          });
          this.getfixedRule();
        })
        .catch(() => {});
    },

    getReasonTypeOptions() {
      const reasonTypeOptions = [];
      const { CHANGE_TYPE_MAP } = this;
      for (let [value, label] of Object.entries(CHANGE_TYPE_MAP)) {
        reasonTypeOptions.push(
          {
            value,
            label: this.$t(label)
          }
        )
      }
      this.reasonTypeOptions = reasonTypeOptions;
    },

    // 获取固定数据
    getfixedRule() {
      fixedRuleData()
        .then(result => {
          if (result.code === 200) {
            this.allFixedRules = result.data.map(item => {
              let fixedRule = '';
              item.combineRule.forEach((childItem, index) => {
                fixedRule += `${childItem.ruleName}${childItem.periodOfTime}${
                  childItem.frequency
                }${childItem.operator}${childItem.value}  ${
                  index < item.combineRule.length - 1 ? 'and' : ''
                }  `;
              });
              item.fixedRule = fixedRule;
              return item;
            });
          } else {
            this.$message.error(result.msg);
          }
        })
        .catch(() => {});
    },

    // 切换分页
    changePagination() {
      this.rulesSearch();
    },

    // 改变事件规则,获取时间\频道\操作,清除原来选好的值
    changeRule(data, rule) {
      let isInputValue = false; // 可输入value值
      Object.keys(this.allRulesData).forEach(key => {
        this.allRulesData[key].forEach(item => {
          if (item.ruleType == rule[0] && item.ruleName == rule[1]) {
            this.times = item.periodOfTime;
            this.frequencys = item.frequency;
            this.operators = item.operator;
            data.periodOfTime =
              item.periodOfTime.length > 0 ? item.periodOfTime[0] : '';
            data.frequency = item.frequency.length > 0 ? item.frequency[0] : '';
            data.operator = item.operator.length > 0 ? item.operator[0] : '';
            isInputValue = item.operator.length === 0;
          }
        });
      });
      // 重置规则
      data.value = '';
      data.disabled = isInputValue;
    },

    // 新增规则
    addRule() {
      this.totalLen++;
      const lastIndex = this.search.length - 1;
      if (this.totalLen === 5) {
        this.$message.info('搜索规则条数不能大于5条');
      }
      if (this.totalLen < 6) {
        this.search[lastIndex].push({
          eventRules: [],
          periodOfTime: '',
          frequency: '',
          operator: '',
          value: '',
          logOperator: 'AND' // 运算符关系
        });
      }
    },

    // 改变搜索规则的运算符
    changeLog(rule, operator, f_index, s_index) {
      if (operator == 'OR') {
        // 处理选择or逻辑,将当前规则[包含后面规则],从当前规则组分离到下一个规则组,删除原来规则组点击规则[包含后面的规则]
        const orData = this.search[f_index].splice(
          s_index,
          this.search[f_index].length - s_index
        );
        this.search[f_index].splice(
          s_index,
          this.search[f_index].length - s_index
        );
        this.search.splice(f_index + 1, 0, orData);
      } else {
        // 处理选择and逻辑,将当前or搜索的规则组合并到上一条规则组,删除原来的or的规则组
        // eslint-disable-next-line no-unused-vars
        const andData = this.search[f_index].forEach(item => {
          this.search[f_index - 1].push(item);
        });
        this.search.splice(f_index, 1);
      }
    },

    // 删除新建的规则
    deleteRule(operator, f_index, s_index) {
      if (operator === 'AND') {
        // 直接删除
        this.search[f_index].splice(s_index, 1);
      } else {
        // 将or后面的and规则将and改成or，再将原来的or规则删除
        if (this.search[f_index][s_index + 1]) {
          this.search[f_index][s_index + 1].logOperator = 'OR';
          this.search[f_index].splice(s_index, 1);
        } else {
          this.search.splice(f_index, 1);
        }
      }
      this.totalLen--;
    },

    // 新增固定规则
    addFixedRule(type) {
      const { search } = this;
      if (!search[0][0].eventRules[1]) {
        this.$message.warning('请先选择事件规则,再创建固定规则！');
        return false;
      }
      
      const rule = this.getFormatRules();
      if (rule) {
        addfixedRule({ rule, greyListOrBlackList: type, page: this.pageName })
          .then(result => {
            if (result.code === 200) {
              this.getfixedRule();
              this.$message.success(result.data);
              this.isShowMore = true;
            } else {
              this.$message.error(result.msg);
            }
          })
          .catch(() => {});
      }
    },

    async beforeDeleteRule(id) {
      try {
          const action = await this.$confirm(
           '确定删除该规则吗？',
           '提示',
            {
              confirmButtonText: this.$t('confirm'),
              cancelButtonText: this.$t('cancel'),
              type: 'warning'
            }
          );

          if (action == 'confirm') {
            this.deleteFixedRules(id);
          }
      } catch(e) {
        throw e;
      }
    },

    // 删除后台固定规则
    deleteFixedRules(id) {
      this.visible = false;
      delfixedRule({ id, page: this.pageName })
        .then(result => {
          if (result.code == 200) {
            this.getfixedRule();
            this.$message.success(result.data);
          } else {
            this.$message.error(result.msg);
          }
        })
        .catch(() => {});
    },

    // 格式化规则数据
    getFormatRules() {
      let flag = false;
      const formatedRules = JSON.parse(JSON.stringify(this.search));
      formatedRules.forEach((f_item, f_index) => {
        f_item.forEach((s_item, s_index) => {
          if (s_item.eventRules[1] === undefined) {
            formatedRules[f_index].splice(s_index, 1);
          } else {
            s_item.ruleType = s_item.eventRules[0];
            s_item.ruleName = s_item.eventRules[1];
            delete s_item.eventRules;
            delete s_item.logOperator;
            if (s_item.value === '' && !s_item.disabled) {
              if (!flag) this.$message.warning('请输入规则数值');
              flag = true;
            } else {
              delete s_item.disabled;
            }
          }
        });
      });
      return flag ? false : formatedRules;
    },

    // 规则搜索
    rulesSearch(type) {
      this.query.pageNum = type == 'search' ? 1 : this.query.pageNum;
      if (this.search[0][0].eventRules[1] === undefined) {
        this.$message.warning('请先选择事件规则，再进行搜索！');
        return false;
      }
      const rule = this.getFormatRules();
      if (rule) {
        this.listLoading = true;
        searchData({
          rule,
          pageIndex: this.query.pageNum,
          pageSize: this.query.pageSize
        })
          .then(result => {
            if (result.code === 200) {
              this.total = result.count;
              this.tableData = this.formatRule(
                JSON.parse(JSON.stringify(result.data))
              );
              this.listLoading = false;
            } else {
              this.listLoading = false;
              this.$message.error(result.msg);
            }
          })
          .catch(() => {
            this.listLoading = false;
          });
      }
    },

    // 重置搜索
    refreshSearch() {
      this.search = JSON.parse(JSON.stringify(searchModel));
      this.totalLen = 1;
      this.reasonType = null;
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
  height: calc(100vh-50px);
  overflow-y: auto;
  & /deep/ .el-timeline-item__node--normal {
    width: 20px;
    height: 2px;
    left: 2px;
    top: 10px;
  }
  & /deep/ .el-timeline-item__tail {
    top: 10px;
  }
  & /deep/ .el-timeline-item {
    padding-bottom: 5px;
  }
}
.el-col {
  padding: 10px;
}
.text-align {
  &--right {
    text-align: right;
  }
}
.cursor {
  &-pointer {
    cursor: pointer;
  }
}
.error {
  color: #f56c6c;
}
.width {
  &-180 {
    width: 180px;
  }
  &-160 {
    width: 160px;
  }
  &-120 {
    width: 120px;
  }
  &-80 {
    width: 80px;
  }
}
.margin {
  &-top {
    &--35 {
      margin-top: 35px;
    }
    &--10 {
      margin-top: 10px;
    }
  }
  &-right {
    &--10 {
      margin-right: 10px;
    }
    &--15 {
      margin-right: 15px;
    }
  }
}
.padding {
  &-left {
    &--28 {
      padding-left: 28px;
    }
  }
  &-right {
    &--135 {
      padding-right: 135px;
    }
    &--102 {
      padding-right: 102px;
    }
  }
}
.search {
  &-label {
    margin-left: 30px;
    margin-bottom: 10px;
    font-size: 14px;
    color: #606266;
  }
}
.float {
  &-left--55 {
    float: left;
    width: 60%;
  }
  &-left {
    float: left;
  }
  &-clear {
    clear: both;
  }
}
.rule-block--node {
  & /deep/ .el-timeline-item__node {
    display: none;
  }
}
.rules {
  font-size: 14px;
  color: #606266;
  border-top: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  &-body {
    position: relative;
    padding: 4px 65px 4px 15px;
    height: 44px;
    overflow: hidden;
    &--item {
      display: inline-block;
      padding: 10px 2px;
      span {
        padding-right: 8px;
        vertical-align: middle;
      }
    }
    &--isMore {
      height: auto;
      overflow: auto;
    }
    &--more {
      position: absolute;
      right: 14px;
      top: 2px;
    }
  }
}
</style>
